import { ReactElement, useState, useEffect } from 'react'
import { Form, TreeSelect, Col } from 'antd'
import { ConditionSchema } from '@components/schema/condition'
import { DataNode } from 'rc-tree-select/lib/interface'
import { awaitWrap } from '@src/assets/js/tool'
import { getTreeRequest } from './ajax'
const { Item } = Form

// 初始化案由树
async function initTree (setTreeData: (v: DataNode[]) => void): Promise<void> {
  const [e, d] = await awaitWrap(getTreeRequest())
  if (e === null && d !== null) {
    d.unshift({ title: '无', value: '无' })
    setTreeData(d)
  }
}

function Main (): ReactElement {
  const [treeData, setTreeData] = useState<DataNode[]>([])
  useEffect(() => {
    initTree(setTreeData).catch(e => console.error(e))
  }, [])
  return (
    <Col span={8}>
      <Item label='案由' name='cause_action'>
        <TreeSelect treeData={treeData} placeholder='请选择' showSearch allowClear />
      </Item>
    </Col>
  )
}

export function initFormat (f: { [k: string]: any }, t: { [k: string]: any }): void {
  if (typeof f.cause_action === 'string') {
    t.cause_action = f.cause_action
  }
}

export function changeFormat (o: { [k: string]: any }): void {

}

export function getCondition (d: { [k: string]: any }): ConditionSchema[] {
  const condition: ConditionSchema[] = []
  if (typeof d.cause_action === 'string' && d.cause_action.length > 0) {
    if (d.cause_action === '无') {
      condition.push({ k: 'cause_action', o: 'null' })
    } else {
      condition.push({ k: 'cause_action', o: '=', v: d.cause_action })
    }
  }
  return condition
}

export default {
  component: Main,
  initFormat,
  changeFormat,
  getCondition
}
